package service

import (
	"errors"
	"exam_go/model"
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type AdminService struct {
}

type Adminiteminforesp struct {
	Name string `json:"name"`
	ID   int64
}

type GetServiceinforesp struct {
	ID        int64   `json:"id" form:"id" binding:"required"`
	Name      string  `json:"name" form:"name" binding:"required"`
	Price     float64 `json:"price" form:"price" binding:"required"` // 使用 float64 映射 DECIMAL
	Img       string  `json:"img" form:"img" binding:"required"`
	IsOnShelf bool    `json:"IsOnShelf" form:"IsOnShelf" binding:"required"`
	Describe  string  `json:"dscribe" form:"describe" binding:"required"`
	Type      string  `json:"type" form:"type" binding:"required"`
}

func (u AdminService) AddItemsservice(c *gin.Context) (resp *Adminiteminforesp, err error) {
	timestamp := time.Now().Unix()

	var form struct { //其实是items表
		Name      string  `json:"name" form:"name" binding:"required"`
		Describe  string  `json:"describe" form:"describe" binding:"required"`
		Price     float64 `json:"price" form:"price"`
		Img       string  `json:"img" form:"img" binding:"required"`
		Rest      int     `json:"rest" form:"rest"`
		IsOnShelf bool    `json:"isOnShelf" form:"isOnShelf"`
	}

	if err = c.ShouldBind(&form); err != nil {
		return nil, err
	}
	good := &model.Good{
		BaseModel: model.BaseModel{
			ID: timestamp,
		},
		Type:   "item",
		Orders: nil,
		Cart:   nil,
	}
	item := &model.Item{
		BaseModel: model.BaseModel{
			ID: timestamp,
		},
		Name:      form.Name,
		Price:     form.Price,
		Img:       form.Img,
		Rest:      form.Rest,
		IsOnShelf: form.IsOnShelf,
		Describe:  form.Describe,
	}
	if err = model.DB.Create(item).Error; err != nil {
		return nil, err
	}
	if err = model.DB.Create(good).Error; err != nil {
		return nil, err
	}
	return &Adminiteminforesp{
		Name: item.Name,
		ID:   item.ID,
	}, nil
}

type AdminServiceinforesp struct {
	Name string `json:"name"`
	ID   int64
}

func (u AdminService) AddServiceservice(c *gin.Context) (resp *AdminServiceinforesp, err error) {
	timestamp := time.Now().Unix()

	var form struct { //其实是Service表
		Name      string  `json:"name" form:"name" binding:"required"`
		Price     float64 `json:"price" form:"price"`
		Img       string  `json:"img" form:"img" binding:"required"`
		IsOnShelf bool    `json:"isOnShelf" form:"isOnShelf"`
		Describe  string  `gorm:"column:describe;NOT NULL" json:"describe"`
	}

	// 绑定表单数据
	if err = c.ShouldBind(&form); err != nil {
		return nil, err
	}

	// 创建 Service 记录
	service := &model.Service{
		BaseModel: model.BaseModel{
			ID: timestamp,
		},
		Name:      form.Name,
		Price:     form.Price,
		Img:       form.Img,
		IsOnShelf: form.IsOnShelf,
		Describe:  form.Describe,
	}

	// 在 Service 表中创建记录
	if err = model.DB.Create(service).Error; err != nil {
		return nil, err
	}

	// 创建 Good 记录
	good := &model.Good{
		BaseModel: model.BaseModel{
			ID: timestamp,
		},
		Type:   "service", // 类型设为 service
		Orders: nil,
		Cart:   nil,
	}

	// 在 Good 表中创建记录
	if err = model.DB.Create(good).Error; err != nil {
		return nil, err
	}

	// 返回响应
	return &AdminServiceinforesp{
		Name: service.Name,
		ID:   service.ID,
	}, nil
}

// 这里ID为servicetime表里的主键，自增，初始为1，对应serviceid为service的主键id
type AdminServiceTimeinforesp struct {
	ID        int64     `json:"id"`        // ServiceTime 记录的唯一标识符
	ServiceID int64     `json:"serviceId"` // 关联的服务ID
	Date      time.Time `json:"date"`      // 日期
	Time      time.Time `json:"time"`      // 时间
	Available bool      `json:"available"` // 可用性状态
}

func (u AdminService) AddServiceTimeservice(c *gin.Context) (*AdminServiceTimeinforesp, error) {
	var form struct {
		ServiceID int64     `json:"serviceId" form:"serviceId" binding:"required"`
		Date      time.Time `json:"date" form:"date" binding:"required"`
		Time      time.Time `json:"time" form:"time" binding:"required"`
		Available bool      `json:"available" form:"available" binding:"required"`
	}

	if err := c.ShouldBind(&form); err != nil {
		return nil, err
	}

	serviceTime := &model.ServiceTime{
		BaseModel: model.BaseModel{},
		ServiceID: form.ServiceID,
		Date:      form.Date,
		Time:      form.Time,
		Available: form.Available,
	}

	if err := model.DB.Create(serviceTime).Error; err != nil {
		return nil, err
	}

	return &AdminServiceTimeinforesp{
		ID:        serviceTime.ID,
		ServiceID: serviceTime.ServiceID,
		Date:      serviceTime.Date,
		Time:      serviceTime.Time,
		Available: serviceTime.Available,
	}, nil
}

func (u AdminService) UpdateServiceTimeAvailability(c *gin.Context) (resp *AdminServiceTimeinforesp, err error) {
	var form struct {
		ServiceID int64     `json:"serviceId" form:"serviceId" binding:"required"`
		Date      time.Time `json:"date" form:"date" binding:"required"`
		Time      time.Time `json:"time" form:"time" binding:"omitempty"`
		Available bool      `json:"available" form:"available" binding:"omitempty"` //幽默，传入true可以，false不可以（现在已经改好了）
		// 会因为 false 值而被认为是无效的，因为 false 在布尔上下文中被视为“空”或“无效”。
		//所以就不要用required了
	}

	if err = c.ShouldBind(&form); err != nil {
		return nil, err
	}

	// 查找 ServiceTime 表中对应的记录
	var serviceTime model.ServiceTime
	if err = model.DB.Where("service_id = ? AND date = ?", form.ServiceID, form.Date).First(&serviceTime).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			// 如果 ServiceTime 表中没有找到记录，返回记录未找到的错误
			return nil, fmt.Errorf("record not found")
		}
		// 如果出现其他数据库错误，返回错误
		return nil, err
	}

	// 更新 available 字段
	serviceTime.Available = form.Available
	if err = model.DB.Save(&serviceTime).Error; err != nil {
		return nil, err
	}

	// 返回更新后的 ServiceTime 记录
	return &AdminServiceTimeinforesp{
		ID:        serviceTime.ID,
		ServiceID: serviceTime.ServiceID,
		Date:      serviceTime.Date,
		Available: serviceTime.Available,
	}, nil
}

func (u AdminService) DeleteGoodsservice(c *gin.Context) (err error) {
	var form struct {
		ID int64 `json:"id" form:"id" binding:"required"`
	}

	if err = c.ShouldBind(&form); err != nil {
		return err
	}
	// 删除 Item 表中对应的记录
	if err = model.DB.Where("id = ?", form.ID).Delete(&model.Item{}).Error; err != nil {
		return err
	}

	// 删除 Service 表中对应的记录
	if err = model.DB.Where("id = ?", form.ID).Delete(&model.Service{}).Error; err != nil {
		return err
	}

	// 删除 Good 表中对应的记录
	if err = model.DB.Where("id = ?", form.ID).Delete(&model.Good{}).Error; err != nil {
		return err
	}

	// 删除 Cart 表中对应的记录
	if err = model.DB.Where("good_id = ?", form.ID).Delete(&model.Cart{}).Error; err != nil {
		return err
	}
	return nil
}

type AdminEditIteminforesp struct {
	Name      string  `json:"name"`
	ID        int64   `json:"id"`
	Price     float64 `json:"price"`
	Img       string  `json:"img"`
	IsOnShelf bool    `json:"isOnShelf"`
	Describe  string  `json:"describe"`
	Rest      int     `json:"rest"`
}

func (u AdminService) EditItemservice(c *gin.Context) (resp *AdminEditIteminforesp, err error) {

	var form struct { //其实是items表
		ID        int64   `json:"id" form:"id"`
		Name      string  `json:"name" form:"name"`
		Price     float64 `json:"price" form:"price"`
		Img       string  `json:"img" form:"img"`
		IsOnShelf bool    `json:"isOnShelf" form:"isOnShelf"`
		Describe  string  `json:"describe" form:"describe"`
		Rest      int     `json:"rest" form:"rest"`
	}

	if err = c.ShouldBind(&form); err != nil {
		return nil, err
	}

	// 查找 Service 表中对应的记录
	var item model.Item
	if err = model.DB.Where("id = ?", form.ID).First(&item).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			// 如果 Item 表中也没有找到，返回记录未找到的错误
			return nil, fmt.Errorf("record not found")
		}
		// 如果出现其他数据库错误，返回错误
		return nil, err
	}
	// 如果找到了 Item 表的记录，更新该记录
	item.Name = form.Name
	item.Price = form.Price
	item.Img = form.Img
	item.IsOnShelf = form.IsOnShelf
	item.Describe = form.Describe
	item.Rest = form.Rest
	if err = model.DB.Save(&item).Error; err != nil {
		return nil, err
	}
	// 返回更新后的 Item 记录
	return &AdminEditIteminforesp{
		ID:        item.ID,
		Name:      item.Name,
		Price:     item.Price,
		Img:       item.Img,
		IsOnShelf: item.IsOnShelf,
		Describe:  item.Describe,
		Rest:      item.Rest,
	}, nil
}

type AdminEditServiceinforesp struct {
	ID        int64   `json:"id"`
	Name      string  `json:"name"`
	Price     float64 `json:"price"`
	Img       string  `json:"img"`
	IsOnShelf bool    `json:"isOnShelf"`
	Describe  string  `json:"describe"`
}

func (u AdminService) EditServiceservice(c *gin.Context) (resp *AdminEditServiceinforesp, err error) {
	fmt.Println("?????????????????????")
	var form struct { //其实是items表
		ID        int64   `json:"id" form:"id"`
		Name      string  `json:"name" form:"name"`
		Price     float64 `json:"price" form:"price"`
		Img       string  `json:"img" form:"img"`
		IsOnShelf bool    `json:"isOnShelf" form:"isOnShelf"`
		Describe  string  `json:"describe" form:"describe"`
	}

	if err = c.ShouldBind(&form); err != nil {
		fmt.Println("111111111111111111")
		return nil, err
	}

	// 查找 Service 表中对应的记录
	var service model.Service
	if err = model.DB.Where("id = ?", form.ID).First(&service).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			// 如果 Item 表中也没有找到，返回记录未找到的错误
			fmt.Println("22222222222222222222222")
			return nil, fmt.Errorf("record not found")
		}
		// 如果出现其他数据库错误，返回错误
		return nil, err
	}
	// 如果找到了 Item 表的记录，更新该记录

	service.Name = form.Name
	service.Price = form.Price
	service.Img = form.Img
	service.IsOnShelf = form.IsOnShelf
	service.Describe = form.Describe
	if err = model.DB.Save(&service).Error; err != nil {
		fmt.Println("33333333333333333333333")
		return nil, err
	}
	// 返回更新后的 Item 记录
	return &AdminEditServiceinforesp{
		ID:        service.ID,
		Name:      service.Name,
		Price:     service.Price,
		Img:       service.Img,
		IsOnShelf: service.IsOnShelf,
		Describe:  service.Describe,
	}, nil
}

type QueryUserResp struct {
	Id       int64  `json:"id"`
	Name     string `json:"name"`     // 用户名
	Number   string `json:"number"`   // 用户号码
	Password string `json:"password"` // 用户密码
	IsVIP    bool   `json:"is_vip"`   // 是否为VIP用户
	IsAdmin  bool   `json:"is_admin"` // 是否为管理员
	Status   int    `json:"status"`   // 用户状态
}

func (u AdminService) QueryUserservice(c *gin.Context) ([]QueryUserResp, error) {
	var form struct {
		Id         int64  `json:"id" form:"id"`
		Name       string `json:"name" form:"name"`
		Number     string `json:"number" form:"number"`
		IsVIP      bool   `json:"isVIP" form:"isVIP"`
		IsAdmin    bool   `json:"isAdmin" form:"isAdmin"`
		Status     int    `json:"status" form:"status"`
		Password   string `json:"password" form:"password"`
		QueryFlags struct {
			IsAdmin bool `json:"queryIsAdmin" form:"queryIsAdmin"`
			IsVip   bool `json:"queryIsVip" form:"queryIsVip"`
			Status  bool `json:"queryStatus" form:"queryStatus"`
		} `json:"queryFlags" form:"queryFlags"`
	}

	// 在这里绑定表单数据
	if err := c.ShouldBind(&form); err != nil && err.Error() != "EOF" {
		return nil, err
	}

	// 定义查询条件
	var query *gorm.DB
	query = model.DB.Model(&model.User{})

	// 如果传入为空，查询所有用户
	if form.Name == "" && form.Number == "" && !form.QueryFlags.IsVip && !form.QueryFlags.IsAdmin && !form.QueryFlags.Status {
		// 如果没有传入任何查询条件，直接查询所有用户
	} else {
		// 根据form中的条件动态添加查询条件
		if form.Id != 0 {
			query = query.Where("id = ?", form.Id)
		}
		if form.Name != "" {
			query = query.Where("name LIKE ?", "%"+form.Name+"%")
		}
		if form.Number != "" {
			query = query.Where("number = ?", form.Number)
		}
		if form.QueryFlags.IsVip {
			query = query.Where("isVip = ?", form.IsVIP)
		}
		if form.QueryFlags.IsAdmin {
			query = query.Where("isAdmin = ?", form.IsAdmin)
		}
		if form.QueryFlags.Status {
			query = query.Where("status = ?", form.Status)
		}
	}

	// 执行查询
	var users []model.User
	if err := query.Find(&users).Error; err != nil {
		return nil, err
	}

	// 将查询结果转换为返回结构体
	var resp []QueryUserResp
	for _, user := range users {
		resp = append(resp, QueryUserResp{
			Id:       user.ID,
			Name:     user.Name,
			Number:   user.Number,
			IsVIP:    user.IsVIP,
			IsAdmin:  user.IsAdmin,
			Status:   user.Status,
			Password: user.Password,
		})
	}
	return resp, nil
}

type itemsRankres struct {
	List []itemrank `json:"list"`
}

type itemrank struct {
	GoodsName string  `json:"goodsName"`
	Count     int64   `json:"count"`
	Money     float64 `json:"money"`
}

type getTotalRevenueres struct {
	Total float64 `json:"total"`
}

func (u UserService) HandleGetItemTimeRangeService(c *gin.Context) (resp *itemsRankres, err error) {
	var uri struct {
		TimeRange string `form:"timeRange" json:"timeRange" binding:"required"`
	}

	// 绑定参数
	if err := c.ShouldBindQuery(&uri); err != nil {
		return nil, err
	}

	// 设定时间范围
	var timeBoundary time.Time
	now := time.Now()
	if uri.TimeRange == "week" {
		timeBoundary = now.AddDate(0, 0, -7)
	} else if uri.TimeRange == "month" {
		timeBoundary = now.AddDate(0, -3, 0)
	} else {
		return nil, errors.New("invalid time range")
	}

	// 查询 orders 表中满足时间和状态条件的记录，仅限 type 为 item 的前五商品
	var results []struct {
		GoodID int64
		Count  int64
		Money  float64
	}
	if err := model.DB.Table("orders").
		Select("good_id, SUM(number) as count, SUM(number * items.price) as money").
		Joins("JOIN goods ON orders.good_id = goods.id").
		Joins("JOIN items ON goods.id = items.id").
		Where("orders.created_at >= ? AND orders.status = 3 AND goods.type = 'item'", timeBoundary).
		Group("good_id").
		Order("count DESC").
		Limit(5).
		Scan(&results).Error; err != nil {
		return nil, err
	}

	// 获取商品名称并构建返回结果
	resp = &itemsRankres{}
	for _, r := range results {
		var name string
		if err := model.DB.Table("items").Select("name").Where("id = ?", r.GoodID).Scan(&name).Error; err != nil {
			return nil, err
		}
		resp.List = append(resp.List, itemrank{
			GoodsName: name,
			Count:     r.Count,
			Money:     r.Money,
		})
	}

	return resp, nil
}

func (u UserService) HandleGetServiceTimeRangeService(c *gin.Context) (resp *itemsRankres, err error) {
	var uri struct {
		TimeRange string `form:"timeRange" json:"timeRange" binding:"required"`
	}

	// 绑定参数
	if err := c.ShouldBindQuery(&uri); err != nil {
		return nil, err
	}

	// 设定时间范围
	var timeBoundary time.Time
	now := time.Now()
	if uri.TimeRange == "week" {
		timeBoundary = now.AddDate(0, 0, -7)
	} else if uri.TimeRange == "month" {
		timeBoundary = now.AddDate(0, -3, 0)
	} else {
		return nil, errors.New("invalid time range")
	}

	// 查询 orders 表中满足时间和状态条件的记录，仅限 type 为 service 的前五商品
	var results []struct {
		GoodID int64
		Count  int64
		Money  float64
	}
	if err := model.DB.Table("orders").
		Select("good_id, SUM(number) as count, SUM(number * services.price) as money").
		Joins("JOIN goods ON orders.good_id = goods.id").
		Joins("JOIN services ON goods.id = services.id").
		Where("orders.created_at >= ? AND orders.status = 3 AND goods.type = 'service'", timeBoundary).
		Group("good_id").
		Order("count DESC").
		Limit(5).
		Scan(&results).Error; err != nil {
		return nil, err
	}

	// 获取商品名称并构建返回结果
	resp = &itemsRankres{}
	for _, r := range results {
		var name string
		if err := model.DB.Table("services").Select("name").Where("id = ?", r.GoodID).Scan(&name).Error; err != nil {
			return nil, err
		}
		resp.List = append(resp.List, itemrank{
			GoodsName: name,
			Count:     r.Count,
			Money:     r.Money,
		})
	}

	return resp, nil
}

func (u UserService) HandleGetTotalRevenueService(c *gin.Context) (resp *getTotalRevenueres, err error) {
	// 初始化总收入
	totalRevenue := 0.0

	// 查询 orders 表中所有 status 为 3 的记录
	var orders []model.Order
	if err := model.DB.Where("status = ?", 3).Find(&orders).Error; err != nil {
		return nil, err
	}

	// 遍历所有订单
	for _, order := range orders {
		// 根据 good_id 查询商品信息
		var good model.Good
		if err := model.DB.Where("id = ?", order.GoodID).First(&good).Error; err != nil {
			return nil, err
		}

		// 获取商品的价格，并计算该订单的收入
		var price float64
		if good.Type == "item" {
			// 如果是 item 类型，查询 items 表
			var item model.Item
			if err := model.DB.Where("id = ?", order.GoodID).First(&item).Error; err != nil {
				return nil, err
			}
			price = item.Price
		} else if good.Type == "service" {
			// 如果是 service 类型，查询 services 表
			var service model.Service
			if err := model.DB.Where("id = ?", order.GoodID).First(&service).Error; err != nil {
				return nil, err
			}
			price = service.Price
		}

		// 计算该订单的收入并累加到总收入中
		totalRevenue += price * float64(order.Number)
	}

	// 返回总收入
	resp = &getTotalRevenueres{
		Total: totalRevenue,
	}
	return resp, nil
}

type getTotalOrdersres struct {
	Total int `json:"total"`
}

func (u UserService) HandleGetTotalOrdersService(c *gin.Context) (resp *getTotalOrdersres, err error) {
	// 查询 orders 表中所有记录的总数
	var total int64
	if err := model.DB.Model(&model.Order{}).Count(&total).Error; err != nil {
		return nil, err
	}

	// 将 total 转换为 int 并返回
	resp = &getTotalOrdersres{
		Total: int(total),
	}
	return resp, nil
}

type getTotalUsersres struct {
	Total int `json:"total"`
}

func (u UserService) HandleGetTotalUsersService(c *gin.Context) (resp *getTotalUsersres, err error) {
	// 查询 users 表的记录总数
	var total int64
	if err := model.DB.Model(&model.User{}).Count(&total).Error; err != nil {
		return nil, err
	}

	// 返回结果
	resp = &getTotalUsersres{
		Total: int(total),
	}

	return resp, nil
}

type getTotalRefunds struct {
	Total float64 `json:"total"`
}

func (u UserService) HandleGetTotalRefundsService(c *gin.Context) (resp *getTotalRefunds, err error) {
	var totalRefunds float64

	// 查询所有 status 为 2 的订单记录
	var orders []model.Order
	if err := model.DB.Where("status = ?", 2).Find(&orders).Error; err != nil {
		return nil, err
	}

	// 遍历查询到的订单
	for _, order := range orders {
		// 根据 good_id 查询对应的商品信息
		var good model.Good
		if err := model.DB.Where("id = ?", order.GoodID).First(&good).Error; err != nil {
			return nil, err
		}

		var price float64
		// 如果商品是类型为 item，查询 items 表
		if good.Type == "item" {
			var item model.Item
			if err := model.DB.Where("id = ?", order.GoodID).First(&item).Error; err != nil {
				return nil, err
			}
			price = item.Price
		} else if good.Type == "service" { // 如果商品是类型为 service，查询 services 表
			var service model.Service
			if err := model.DB.Where("id = ?", order.GoodID).First(&service).Error; err != nil {
				return nil, err
			}
			price = service.Price
		}

		// 计算退款金额：price * number
		totalRefunds += price * float64(order.Number)
	}

	// 返回结果
	resp = &getTotalRefunds{
		Total: totalRefunds,
	}

	return resp, nil
}

// 查询商品状态
type GetItemStatusinforesp struct {
	ID        int64   `json:"id" form:"id" binding:"required"`
	Name      string  `json:"name" form:"name" binding:"required"`
	Describe  string  `json:"describe" form:"describe" binding:"required"`
	Price     float64 `json:"price" form:"price" binding:"required"`
	Img       string  `json:"img" form:"img" binding:"required"`
	Rest      int     `json:"rest" form:"rest" binding:"required"`
	IsOnShelf bool    `json:"isOnShelf" form:"isOnShelf" binding:"required"`
}

func (u AdminService) GetItemStatus(c *gin.Context) (resp *GetItemStatusinforesp, err error) {
	var form struct { // 其实是items表
		ID        int64   `json:"id" form:"id" binding:"required"`
		Name      string  `json:"name" form:"name" binding:"omitempty"`
		Price     float64 `json:"price" form:"price" binding:"omitempty"`
		Img       string  `json:"img" form:"img" binding:"omitempty"`
		IsOnShelf bool    `json:"isOnShelf" form:"isOnShelf" binding:"omitempty"`
		Describe  string  `json:"describe" form:"describe" binding:"omitempty"`
		Rest      int     `json:"rest" form:"rest" binding:"omitempty"`
	}

	if err = c.ShouldBind(&form); err != nil {
		return nil, err
	}

	// 尝试查找 Item 表中的记录
	var item model.Item
	if err = model.DB.Where("id = ?", form.ID).First(&item).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			// 如果 Item 表中没有找到，返回记录未找到的错误
			return nil, fmt.Errorf("record not found")
		}
		// 如果出现其他数据库错误，返回错误
		return nil, err
	}

	// 返回查询到的 Item 记录
	return &GetItemStatusinforesp{
		ID:        item.ID,
		Name:      item.Name,
		Price:     item.Price,
		Img:       item.Img,
		IsOnShelf: item.IsOnShelf,
		Describe:  item.Describe,
		Rest:      item.Rest,
	}, nil
}

// 查询服务信息

func (u AdminService) GetServiceInfo(c *gin.Context) (resp *GetServiceinforesp, err error) {

	var form struct {
		ID        int64   `json:"id" form:"id" binding:"required"`
		Name      string  `json:"name" form:"name" binding:"required"`
		Price     float64 `json:"price" form:"price" binding:"required"` // 使用 float64 映射 DECIMAL
		Img       string  `json:"img" form:"img" binding:"required"`
		IsOnShelf bool    `json:"IsOnShelf" form:"IsOnShelf" binding:"required"`
		Describe  string  `json:"dscribe" form:"describe" binding:"required"`
	}

	if err = c.ShouldBind(&form); err != nil {
		return nil, err
	}

	// 尝试查找 Item 表中的记录
	var service model.Service
	if err = model.DB.Where("id = ?", form.ID).First(&service).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			// 如果 Item 表中没有找到，返回记录未找到的错误
			return nil, fmt.Errorf("record not found")
		}
		// 如果出现其他数据库错误，返回错误
		return nil, err
	}

	// 返回查询到的 Item 记录
	return &GetServiceinforesp{

		ID:        service.ID,
		Name:      service.Name,
		Price:     service.Price,
		Img:       service.Img,
		Describe:  service.Describe,
		IsOnShelf: service.IsOnShelf,
	}, nil
}

type GetOrderInforesp struct {
	List []OrderssList `json:"list"`
}

type OrderssList struct {
	ID        int64     `json:"id" form:"id" binding:"required"`
	Name      string    `json:"name" form:"name" binding:"required"`
	Status    int       `json:"status" form:"State" binding:"required"`
	CreatedAt time.Time `json:"createdAt" form:"createdAt" binding:"required"`
	UserID    int64     `json:"userID" form:"userID" binding:"required"`
}

type Status int

const (
	Cancelled Status = 0
	Unpaid    Status = 1
	Paid      Status = 2
	Finish    Status = 3
)

func (u AdminService) GetOrderInfo(c *gin.Context) (resp *GetOrderInforesp, err error) {
	// 定义参数结构体
	var form struct {
		ID     *int64 `json:"id" form:"id"`         // 使用指针以判断参数是否传递
		Status *int   `json:"status" form:"status"` // 使用指针以区分未传值和传值（包括 0）
		Name   string `json:"name" form:"name"`
	}

	// 绑定参数
	if err := c.ShouldBind(&form); err != nil {
		return nil, err
	}

	// 初始化返回结果
	resp = &GetOrderInforesp{}
	query := model.DB.Model(&model.Order{})

	// 如果 ID 参数有效且不为空，则根据 ID 筛选
	if form.ID != nil && *form.ID != 0 {
		query = query.Where("id = ?", *form.ID)
	}

	// 如果 Status 参数有效，则根据 Status 筛选
	if form.Status != nil { // Status 有效性直接判断是否为 nil
		query = query.Where("status = ?", *form.Status)
	}

	// 如果 Name 参数非空字符串，则根据 Name 模糊查询
	if form.Name != "" {
		itemQuery := model.DB.Model(&model.Item{}).Select("id").Where("name LIKE ?", "%"+form.Name+"%")
		serviceQuery := model.DB.Model(&model.Service{}).Select("id").Where("name LIKE ?", "%"+form.Name+"%")
		query = query.Where("good_id IN (?) OR good_id IN (?)", itemQuery, serviceQuery)
	}

	// 执行查询
	var orders []model.Order
	if err := query.Find(&orders).Error; err != nil {
		return nil, err
	}

	// 构造返回结果
	for _, order := range orders {
		// 获取 good_id 对应的 name
		var name string
		if err := model.DB.Raw(`
			SELECT name FROM items WHERE id = ? UNION SELECT name FROM services WHERE id = ?
		`, order.GoodID, order.GoodID).Scan(&name).Error; err != nil {
			return nil, err
		}

		// 构造订单信息
		orderInfo := OrderssList{
			ID:        order.ID,
			Name:      name,
			Status:    order.Status,
			CreatedAt: order.CreatedAt,
			UserID:    order.UserID,
		}

		resp.List = append(resp.List, orderInfo)
	}

	return resp, nil
}

type GetAllItemsResp struct {
	List []GetAllIteminforesp `json:"list"`
}

type GetAllIteminforesp struct {
	ID        int64   `json:"id" form:"id" binding:"required"`
	Name      string  `json:"name" form:"name" binding:"required"`
	Price     float64 `json:"price" form:"price" binding:"required"`
	Img       string  `json:"img" form:"img" binding:"required"`
	Type      string  `json:"type" form:"type" binding:"required"`
	IsOnShelf bool    `json:"isOnShelf" form:"isOnShelf" binding:"required"`
	Describe  string  `json:"describe" form:"describe" binding:"required"`
}

func (u AdminService) GetAllItem(c *gin.Context) (resp *GetAllItemsResp, err error) {
	// 查询 items 表中的所有记录，注意字段名称匹配
	var items []model.Item
	if err := model.DB.Model(&model.Item{}).Select("id", "name", "price", "img", "isOnShelf", "describe").Find(&items).Error; err != nil {
		return nil, err
	}

	// 将 Type 字段手动设为 "item"
	var itemRespList []GetAllIteminforesp
	for _, item := range items {
		itemRespList = append(itemRespList, GetAllIteminforesp{
			ID:        item.ID,
			Name:      item.Name,
			Price:     item.Price,
			Img:       item.Img,
			Type:      "item", // Type 字段固定为 "item"
			IsOnShelf: item.IsOnShelf,
			Describe:  item.Describe,
		})
	}

	// 返回结果
	resp = &GetAllItemsResp{
		List: itemRespList,
	}

	return resp, nil
}
func (u AdminService) GetAllService(c *gin.Context) (resp *GetAllItemsResp, err error) {

	// 查询 services 表中的所有记录，注意字段名称匹配
	var services []model.Service
	if err := model.DB.Model(&model.Service{}).Select("id", "name", "price", "img", "isOnShelf", "describe").Find(&services).Error; err != nil {
		return nil, err
	}

	// 将 Type 字段手动设为 "service"
	var serviceRespList []GetAllIteminforesp
	for _, service := range services {
		serviceRespList = append(serviceRespList, GetAllIteminforesp{
			ID:        service.ID,
			Name:      service.Name,
			Price:     service.Price,
			Img:       service.Img,
			Type:      "service", // Type 字段固定为 "item"
			IsOnShelf: service.IsOnShelf,
			Describe:  service.Describe,
		})
	}

	// 返回结果
	resp = &GetAllItemsResp{
		List: serviceRespList,
	}

	return resp, nil

}

func (u AdminService) GetAllInfoByID(c *gin.Context) (resp []GetServiceinforesp, err error) {
	var form struct {
		ID int64 `json:"id" form:"id" binding:"required"`
	}

	if err = c.ShouldBind(&form); err != nil {
		return nil, err
	}

	// 查询两个表中的全部信息
	if err = model.DB.Table("services").
		Select("services.*, items.*").
		Joins("LEFT JOIN items ON services.id = items.id").
		Where("services.id = ? OR items.id = ?", form.ID, form.ID).
		Scan(&resp).Error; err != nil {
		return nil, err
	}

	return resp, nil
}

func (u AdminService) GetAllInfoByName(c *gin.Context) (resp *GetAllItemsResp, err error) {
	var form struct {
		Name string `json:"name" form:"name"`
	}

	// 绑定前端传递的参数
	if err := c.ShouldBindQuery(&form); err != nil {
		return nil, err
	}

	// 定义查询条件，选择 items 表和 services 表
	var query *gorm.DB
	if form.Name != "" {
		// 如果传递了 Name，则进行模糊查询
		query = model.DB.Model(&model.Item{}).
			Where("name LIKE ?", "%"+form.Name+"%").
			Select("id, name, price, img,  'item' as type, isOnShelf, `describe`")

		// 同时查询 services 表
		serviceQuery := model.DB.Model(&model.Service{}).
			Where("name LIKE ?", "%"+form.Name+"%").
			Select("id, name, price, img, 'service' as type, isOnShelf, `describe`")

		// 合并查询两个表
		query = model.DB.Raw("(?) UNION ALL (?)", query, serviceQuery)
	} else {
		// 如果没有传递 Name，查询所有 items 和 services 表
		query = model.DB.Model(&model.Item{}).
			Select("id, name, price, img, 'item' as type, isOnShelf, `describe`")

		// 同时查询 services 表
		serviceQuery := model.DB.Model(&model.Service{}).
			Select("id, name, price, img, 'service' as type, isOnShelf, `describe`")

		// 合并查询两个表
		query = model.DB.Raw("(?) UNION ALL (?)", query, serviceQuery)
	}

	// 执行查询
	var alls []GetAllIteminforesp
	if err := query.Scan(&alls).Error; err != nil {
		return nil, err
	}

	// 将查询结果转换为 GetAllIteminforesp 格式
	var allRespList []GetAllIteminforesp
	for _, all := range alls {
		allRespList = append(allRespList, GetAllIteminforesp{
			ID:        all.ID,
			Name:      all.Name,
			Price:     all.Price,
			Img:       all.Img,
			Type:      all.Type,
			IsOnShelf: all.IsOnShelf,
			Describe:  all.Describe,
		})
	}

	// 返回结果
	resp = &GetAllItemsResp{
		List: allRespList,
	}

	return resp, nil
}

type GetTotalReportinforesp struct {
	ID        int64     `json:"id" form:"id" binding:"required"`
	Status    int       `json:"status" form:"status" binding:"required"`
	GoodName  string    `json:"goodName" form:"goodName" binding:"required"`
	CreatedAt time.Time `json:"createdAt" form:"createdAt" binding:"required"`
	Price     float64   `json:"price" form:"price" binding:"required"`
	UserName  string    `json:"userName" form:"userName" binding:"required"`
	Phone     string    `json:"phone" form:"phone" binding:"required"`
	IsVIP     bool      `json:"isVIP" form:"isVIP" binding:"required"`
}

func (u AdminService) GetTotalReport(c *gin.Context) (resp []GetTotalReportinforesp, err error) {
	var form struct {
	}

	if err = c.ShouldBind(&form); err != nil {
		return nil, err
	}

	query := model.DB.Table("orders").
		Select("orders.ID, orders.Status, COALESCE(services.Name, items.Name) AS GoodName, orders.created_at, COALESCE(services.price, items.price) AS Price, users.Name AS UserName, users.Number AS Phone, users.isVIP").
		Joins("JOIN users ON orders.user_id = users.id").
		Joins("JOIN goods ON orders.good_id = goods.id").
		Joins("LEFT JOIN services ON goods.id = services.id").
		Joins("LEFT JOIN items ON goods.id = items.id")
	if err = query.Scan(&resp).Error; err != nil {
		return nil, err
	}

	return resp, nil

}

type AdminEditUsersinforesp struct {
	Number   string `json:"number" form:"number"`
	Name     string `json:"name" form:"name"`
	IsVIP    bool   `json:"isVIP" form:"isVIP"`
	Status   int    `json:"status" form:"status"`
	Password string `json:"password" form:"password"`
	IsAdmin  bool   `json:"isAdmin" form:"isAdmin"`
}

func (u AdminService) EditUsers(c *gin.Context) (resp *AdminEditUsersinforesp, err error) {

	var form struct { //其实是USERS表
		Number   string `json:"number" form:"number" `
		Name     string `json:"name" form:"name" `
		IsVIP    bool   `json:"isVIP" form:"isVIP" `
		Status   int    `json:"status" form:"status" `
		Password string `json:"password" form:"password"`
		IsAdmin  bool   `json:"isAdmin" form:"isAdmin"`
	}

	if err = c.ShouldBind(&form); err != nil {
		return nil, err
	}

	// 查找 Service 表中对应的记录
	var users model.User
	if err = model.DB.Where("number = ?", form.Number).First(&users).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			// 如果 Item 表中也没有找到，返回记录未找到的错误
			return nil, fmt.Errorf("record not found")
		}
		// 如果出现其他数据库错误，返回错误
		return nil, err
	}
	// 如果找到了 Item 表的记录，更新该记录
	users.Number = form.Number
	users.Name = form.Name
	users.IsVIP = form.IsVIP
	users.Status = form.Status
	users.Password = form.Password
	users.IsAdmin = form.IsAdmin
	if err = model.DB.Save(&users).Error; err != nil {
		return nil, err
	}
	// 返回更新后的 Item 记录
	return &AdminEditUsersinforesp{
		Number:   users.Number,
		Name:     users.Name,
		IsVIP:    users.IsVIP,
		Status:   users.Status,
		Password: users.Password,
		IsAdmin:  users.IsAdmin,
	}, nil
}

func (u AdminService) EditOrder(c *gin.Context) (err error) {

	var form struct { //其实是USERS表
		ID     int64 `json:"id" form:"id" binding:"required"`
		Status int   `json:"status" form:"status" `
	}

	if err = c.ShouldBind(&form); err != nil {
		return err
	}

	// 查找对应的订单
	var order model.Order
	result := model.DB.First(&order, form.ID)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return fmt.Errorf("订单不存在")
		}
		return result.Error
	}
	// 更新订单状态
	order.Status = form.Status
	result = model.DB.Save(&order)
	if result.Error != nil {
		return result.Error
	}
	return nil
}

type SearchGoodsResponsee struct {
	Total int64        `json:"total"`
	List  []GoodsListt `json:"list"` // 商品列表
}

type GoodsListt struct {
	ID        int64   `json:"id"`
	Type      string  `json:"type"`     // 商品类型
	Img       string  `json:"img"`      // 商品图片
	Price     float64 `json:"price"`    // 商品价格1
	Name      string  `json:"name"`     // 商品名称
	Describe  string  `json:"describe"` // 商品描述
	IsOnShelf bool    `json:"isOnShelf"`
}

func (u AdminService) GetGoods(c *gin.Context) (resp *SearchGoodsResponsee, err error) {
	// 定义查询参数结构体
	var uri struct {
		Name string `form:"name" json:"name" uri:"name"` // 支持模糊查询的 name 参数
	}

	// 绑定请求参数
	if err := c.ShouldBindQuery(&uri); err != nil {
		return nil, err
	}

	// 初始化返回结构体
	resp = &SearchGoodsResponsee{
		Total: 0,
		List:  []GoodsListt{},
	}

	// 定义存储查询结果的切片
	var items []model.Item
	var services []model.Service

	// 查询 items 表
	if err := model.DB.Where("name LIKE ?", "%"+uri.Name+"%").Find(&items).Error; err != nil {
		return nil, fmt.Errorf("failed to query items: %v", err)
	}

	// 查询 services 表
	if err := model.DB.Where("name LIKE ?", "%"+uri.Name+"%").Find(&services).Error; err != nil {
		return nil, fmt.Errorf("failed to query services: %v", err)
	}

	// 处理 items 表的结果
	for _, item := range items {
		resp.List = append(resp.List, GoodsListt{
			ID:        item.ID,
			Type:      "item",
			Img:       item.Img,
			Price:     item.Price,
			Name:      item.Name,
			Describe:  item.Describe,
			IsOnShelf: item.IsOnShelf,
		})
	}

	// 处理 services 表的结果
	for _, service := range services {
		resp.List = append(resp.List, GoodsListt{
			ID:        service.ID,
			Type:      "service",
			Img:       service.Img,
			Price:     service.Price,
			Name:      service.Name,
			Describe:  service.Describe,
			IsOnShelf: service.IsOnShelf,
		})
	}

	// 设置总记录数
	resp.Total = int64(len(resp.List))

	return resp, nil
}
